package com.myblog.service;

import com.myblog.entity.Article;
import com.myblog.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public void setArticleRank(List<Article> articleList) {
        //从redis取出文章排序
        List redis_Article_Rank = redisUtil.zrange("BLOG:ARTICLE_RANK", 0, -1);
        if (redis_Article_Rank.size() <= 0) {
            for (Article article : articleList) {
                redisUtil.zadd("BLOG:ARTICLE_RANK", article, article.getCreateTime().getTime());
            }
        }
    }

    /**
     * 以hash形式存入文章id和view
     *
     * @param articleList
     */
    @Override
    public void setArticleView(List<Article> articleList) {
        //从redis中取出阅读量
        Map redis_View = redisUtil.hentries("BLOG:ARTICLE_VIEW");
        if (redis_View.size() <= 0) {
            for (Article article : articleList) {
                redisUtil.hset("BLOG:ARTICLE_VIEW", String.valueOf(article.getId()), article.getViews());
            }
        }
    }
}
